package com.isoft.demo01.controller;

import com.isoft.demo01.bean.BaseController;
import com.isoft.demo01.bean.ResponseData;
import com.isoft.demo01.bean.ResultCode;
import com.isoft.demo01.entity.Game;
import com.isoft.demo01.service.impl.GameImplService;
import com.isoft.demo01.util.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("find/game")
public class GameController extends BaseController {
    @Autowired
    GameImplService gameImplService;
    @Value("${sys.game.uppath}")
    private String gamephotopath;
    List<String> gamePhotoNames=new ArrayList<>();
    @RequestMapping("page")
    public Map<String,Object> findgame(Integer gameid,String gamename,Integer page,Integer size){
        Map<String,Object> map=gameImplService.gamepage(gameid, gamename, page, size);
        map.put("code",0);
        map.put("msg","");
        return map;
    }
    @PostMapping("add")
    public ResponseData add(Game game){
        boolean r=false;
        if (null!=game){
            if (gamePhotoNames.size()>0){
                game.setPhoto(gamePhotoNames.toString().substring(1,gamePhotoNames.toString().length()-1));
                gamePhotoNames.clear();
            }
            r=gameImplService.add(game);
        }
        return getResponseData(r);
    }
    @PostMapping("img")
    public Map upGamePhoto(MultipartFile file, HttpServletRequest request){
        String[] url=null;
        if (null!= file){
            url= FileUtil.uploadFile(file,null,gamephotopath,request);
        }
        Map<String,Object> map=new HashMap<>();
        if (null!=url){
            gamePhotoNames.add(url[1]);
            Map<String,String> data=new HashMap<>();
            data.put("src",url[0]);
            data.put("title","游戏图片");
            map.put("code",0);
            map.put("msg","上传成功");
            map.put("data",data);
        }else {
            map.put("code",1);
            map.put("msg","上传失败");
            map.put("data",null);
        }
        return map;
    }
    @GetMapping("findmenu")
    public ResponseData findmenu(Integer typeid){
        ResponseData req=new ResponseData();
        List<Game> game=gameImplService.findmenu(typeid);
        if (game!=null){
            req.setErrorCode(ResultCode.SUCCESS.getCode());
            req.setMsg(ResultCode.SUCCESS.getMessage());
        }else {
            req.setErrorCode(ResultCode.COMMON_FAIL.getCode());
            req.setMsg(ResultCode.COMMON_FAIL.getMessage());
        }
        req.setData(game);
        return req;
    }
}
